package main

import (
	"context"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

//logrus实例
var logIns = log.New()

func init() {

	logFile, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err == nil {
		logIns.SetFormatter(&log.JSONFormatter{})
		logIns.Out = logFile
	} else {
		logIns.Warn("failed to log to file,using default stderr")
	}

}

func main() {
	r := gin.Default()

	r.GET("/ping", func(c *gin.Context) {

		logIns.Info("bar")

		time.Sleep(time.Second * 5)
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})

	srv := &http.Server{Addr: ":8080", Handler: r}

	// Initializing the server in a goroutine so that
	// it won't block the graceful shutdown handling below
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logIns.Fatalf("lisen error:%s\n", err)
		}
	}()

	//go平滑重启
	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal)
	// kill (no param) default send syscall.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	s := <-quit
	logIns.Println(s)
	logIns.Println("shutting down server")

	// The context is used to inform the server it has 5 seconds to finish
	// the request it is currently handling
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		logIns.Fatal("server forced to shutdown :", err)
	}

	logIns.Println("server exiting")
}
